<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>机房管理系统</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            @input="handleInput('username', $event)"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password"
            @input="handleInput('password', $event)"
            placeholder="请输入密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
          <el-button @click="router.push('/register')">没有账号？注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { login } from '../api/auth'
import { ElMessage } from 'element-plus'

// 使用 reactive 创建响应式对象
const loginForm = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

const loginFormRef = ref(null)
const router = useRouter()
const store = useStore()
const loading = ref(false)
// 手动处理输入事件，确保响应式更新
const handleInput = (field, value) => {
  loginForm[field] = value
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    // 验证表单
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    const response = await login(loginForm.username, loginForm.password)
    
    // 确保数据是最新的
    store.dispatch('login', response.data.access_token)
    ElMessage.success('登录成功')
    
    // 清空表单
    loginForm.username = ''
    loginForm.password = ''
    
    router.push('/')
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.detail || '登录失败')
    } else {
      ElMessage.error('登录失败，请稍后重试')
    }
    console.error('Login error:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  font-size: 14px;
}
</style>